#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Flask后端服务器
为前端ECharts图表提供数据接口
"""

from flask import Flask, render_template, jsonify
import sys
import os

# 添加当前目录到Python路径中
sys.path.append(os.path.dirname(os.path.abspath(__file__)))

# 导入我们创建的模块
from data_fetcher import get_sh_index_data
from strategies import ma_strategy, evaluate_strategy
from backtest import backtest_strategy

app = Flask(__name__, template_folder='templates')


@app.route('/')
def index():
    """
    主页面路由
    """
    return render_template('index.html')


@app.route('/api/stock_data')
def stock_data():
    """
    获取股票数据的API接口
    """
    try:
        # 获取上证指数数据
        sh_index_data = get_sh_index_data(start_date="20200101", end_date="20231231")
        
        # 应用双均线策略
        signals = ma_strategy(sh_index_data, short_window=5, long_window=20)
        
        # 评估策略
        strategy_evaluation = evaluate_strategy(signals)
        
        # 回测策略
        backtest_result = backtest_strategy(signals, initial_capital=10000.0)
        
        # 准备返回给前端的数据
        data = {
            'dates': signals['date'].dt.strftime('%Y-%m-%d').tolist(),
            'closes': signals['close'].tolist(),
            'short_ma': signals['short_ma'].tolist(),
            'long_ma': signals['long_ma'].tolist(),
            'buy_signals': [],
            'sell_signals': [],
            'stats': {
                'initial_capital': backtest_result['initial_capital'],
                'final_asset': float(backtest_result['final_asset']),
                'total_return': float(backtest_result['total_return']),
                'total_signals': strategy_evaluation['total_signals'],
                'buy_signals': strategy_evaluation['buy_signals'],
                'sell_signals': strategy_evaluation['sell_signals']
            }
        }
        
        # 提取买入信号
        buy_signals = signals[signals['positions'] == 1.0]
        for _, row in buy_signals.iterrows():
            data['buy_signals'].append({
                'date': row['date'].strftime('%Y-%m-%d'),
                'price': float(row['close'])
            })
        
        # 提取卖出信号
        sell_signals = signals[signals['positions'] == -1.0]
        for _, row in sell_signals.iterrows():
            data['sell_signals'].append({
                'date': row['date'].strftime('%Y-%m-%d'),
                'price': float(row['close'])
            })
        
        return jsonify(data)
    except Exception as e:
        return jsonify({'error': str(e)}), 500


@app.route('/api/stock_data/<start_date>/<end_date>/<int:short_window>/<int:long_window>')
def stock_data_custom(start_date, end_date, short_window, long_window):
    """
    获取自定义参数股票数据的API接口
    """
    try:
        # 获取上证指数数据
        sh_index_data = get_sh_index_data(start_date=start_date, end_date=end_date)
        
        # 应用双均线策略
        signals = ma_strategy(sh_index_data, short_window=short_window, long_window=long_window)
        
        # 评估策略
        strategy_evaluation = evaluate_strategy(signals)
        
        # 回测策略
        backtest_result = backtest_strategy(signals, initial_capital=10000.0)
        
        # 准备返回给前端的数据
        data = {
            'dates': signals['date'].dt.strftime('%Y-%m-%d').tolist(),
            'closes': signals['close'].tolist(),
            'short_ma': signals['short_ma'].tolist(),
            'long_ma': signals['long_ma'].tolist(),
            'buy_signals': [],
            'sell_signals': [],
            'stats': {
                'initial_capital': backtest_result['initial_capital'],
                'final_asset': float(backtest_result['final_asset']),
                'total_return': float(backtest_result['total_return']),
                'total_signals': strategy_evaluation['total_signals'],
                'buy_signals': strategy_evaluation['buy_signals'],
                'sell_signals': strategy_evaluation['sell_signals']
            }
        }
        
        # 提取买入信号
        buy_signals = signals[signals['positions'] == 1.0]
        for _, row in buy_signals.iterrows():
            data['buy_signals'].append({
                'date': row['date'].strftime('%Y-%m-%d'),
                'price': float(row['close'])
            })
        
        # 提取卖出信号
        sell_signals = signals[signals['positions'] == -1.0]
        for _, row in sell_signals.iterrows():
            data['sell_signals'].append({
                'date': row['date'].strftime('%Y-%m-%d'),
                'price': float(row['close'])
            })
        
        return jsonify(data)
    except Exception as e:
        print(f"Error in stock_data_custom: {e}")  # 添加调试信息
        return jsonify({'error': str(e)}), 500


# 添加静态文件路由
@app.route('/static/<path:filename>')
def static_files(filename):
    return app.send_static_file(filename)


if __name__ == '__main__':
    app.run(debug=True, host='0.0.0.0', port=5005)